package allrobots.RobotThread;

import allrobots.Robot.RobotMessage;
import allrobots.Robot.RobotMessageMap;
import allrobots.Robot.RobotsSocketMap;
import allrobots.pojo.BroadcastMessage;
import t10086.Data.Broadcast;
import t10086.Data.Robot.RobotStatus;
import t10086.Model.Messages.Message;
import t10086.Model.Messages.MessageType;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.util.Map;

public class RegularReception implements Runnable {
    Integer robotId;
    private ObjectInputStream ois;

    public RegularReception(Integer robotId) {
        this.robotId = robotId;
        this.ois = RobotsSocketMap.robotsSocketMap.get(robotId).getOis();
    }

    @Override
    public void run() {
        System.out.println(RobotsSocketMap.robotsSocketMap.get(robotId).getSocket().getLocalSocketAddress()+"  "+RobotsSocketMap.robotsSocketMap.get(robotId).getSocket().getLocalPort());
        while (true) {
            Object fromSystem = null;//定期接收系统信息；
            while (fromSystem == null) {
                try {
//                    System.out.println("33333333333333333333333");
                    fromSystem = ois.readObject();
                    if (fromSystem != null) {
                        //接收系统发来信息
                        Message messageSystem = (Message) fromSystem;
//                        System.out.println(messageSystem);
                        if (messageSystem.getType() == MessageType.BROADCAST) {
                            Broadcast broadcast = messageSystem.convertData(Broadcast.class);
                            //定期接收信息，信息规定已完成，未完成广播修改信息
//                            System.out.println(broadcast.getMovingNumber()+"1111111111");
                            BroadcastMessage.broadcastMessage=broadcast;
//                            System.out.println(broadcast.getMovingNumber()+"收到广播");
                        } else if (messageSystem.getType() == MessageType.RESPONSE) {
                            RobotMessage robot1 = RobotMessageMap.robotMap.get(robotId);
                            if(robot1.getRobotStatus()== RobotStatus.FREE){
                                Map<String, Object> responseMap = messageSystem.convertData(Map.class);
                                Long num = (Long) responseMap.get("number");
                                System.out.println("当前机器人序列号" + robot1.getSerialNum() + " " + num);
//                            Long num=messageSystem.convertData(Long.class);
                            }
                        }
                    }
                } catch (IOException | ClassNotFoundException ignored) {
                }
            }
        }
    }
}
